<?php
/**
 * User: wangzd
 * Email: wangzhoudong@liwejia.com
 * Date: 2016/11/30
 * Time: 15:14
 */
namespace LWJ\Services\Oms;

class OmsUser
{

    /**
     * 判断是否登录，如果登录返回用户信息，否则返回false;
     * @return array or bool;
     */
    public static function isLogin($timeout=3) {
        $user = OmsHttpClient::query('services/user/isLogin',array(),$timeout=3);
        $user = json_decode($user,true);

        if(isset($user['result']['id'])) {
            $user = $user['result'];
            if(isset($user['roles']) && $user['roles']) {
                $user['roles'] = array_column($user['roles'],'name');
            }else{
                $user['roles'] = array();
            }
            setcookie("user_is_login","true","0","liweijia.com");
            return $user;
        }else{
            return false;
        }
    }

    /**
     * 登录，方法会执行跳转
     * @param string $redirect 登录成功后返回的地址，http打头，默认当前页面
     */
    public static function login($redirect=null,$sourceSystemCode='www') {
        $url = self::loginUrl($redirect,$sourceSystemCode);

        header("Location: $url");exit;
    }

    /**
     * 退出登录，方法会执行跳转
     * @param string $redirect 退出成功后返回的地址，http打头，默认当前页面
     */
    public static function logout($redirect=null) {
        setcookie("user_is_login",'', '-3600');
        setcookie("user_is_login","false","0","liweijia.com");
        $url = self::logoutUrl($redirect);
        header("Location: $url");exit;
    }

    public static function logoutUrl($redirect=null) {
        if(!$redirect) {
            $redirect = url('/');
        }
        $url = OmsHttpClient::rebuildUrl('security/auth/logout',array('returnUrl'=>$redirect));
        return $url;
    }
    /**
     * 手动获取登录地址
     * @param string $redirect 登录成功后返回的地址，http打头，默认当前页面
     */
    public static function loginUrl($redirect=null,$sourceSystemCode='www') {
        if(!$redirect) {
            $redirect = url('/');

        }

        $url = OmsHttpClient::rebuildUrl('security/auth/login',array('returnUrl'=>($redirect),'systemCode'=>$sourceSystemCode));

        return $url;
    }
    /**
     * 手动获取注册地址
     * @param string $redirect
     * @param string $invite_user_id
     * @return string
     */
    public static function registerUrl($redirect=null, $registReturnUrl=null,$sourceSystemCode='www') {
        if(!$redirect) {
            $redirect = url('/');
        }

        if($registReturnUrl){
            //如果存在注册返回地址，则传入
            $url = OmsHttpClient::rebuildUrl( 'security/auth/register',array('returnUrl'=>$redirect, 'registReturnUrl'=>$registReturnUrl,'sourceSystemCode'=>$sourceSystemCode));
        }else{
            $url = OmsHttpClient::rebuildUrl( 'security/auth/register',array('returnUrl'=>$redirect,'sourceSystemCode'=>$sourceSystemCode));
        }

        return $url;
    }


    /**
     * @param $data
     * {"mobile":"15811468868","name":"15811468868","password":"1470619343271"}

     */
    public static function register($data) {
        if(!isset($data['password'])) {
            //ERP密码必填
            $data['password'] = md5(time()+rand(1111,9999));
        }
        $result = OmsOAuthHttpClient::put('o/ums/user/register', array(), $data);
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0) {
            return array('status'=>200,'data'=>['user_id'=>$data['result']]);
        }else {
            return array('status'=>500,'msg' =>$result);
        }
    }


    /**
     * @param $data
     * {"mobile":"15811468868","name":"15811468868","password":"1470619343271"}

     */
    public static function registerSimple($mobile) {
        $result  = OmsOAuthHttpClient::put('o/ums/user/' . $mobile . '/register/simple');
        var_dump($result);exit;
        $result = json_decode($result,true);
        if(isset($result['code']) && $result['code'] == 0) {
            return array('status'=>200,'data'=>['user_id'=>$result['result']]);
        }else {
            return array('status'=>500,'msg' =>$result['messages']);
        }
    }


    public static function searchUserInfo($data)
    {
        $queryUrl = 'o/ums/user/list/' . (isset($data['limit']) ? $data['limit'] : PAGE_MAX_NUMS) .
            '/' . (isset($data['page']) ? $data['page'] : 1) .
            '/' . (isset($data['sort']) ? $data['sort'] : 'createTime') .
            '/' . (isset($data['order']) ? $data['order'] : 'DESC');
        $result = OmsOAuthHttpClient::put($queryUrl, [], $data);
        $data = json_decode($result, true);
        if( !isset($data['items']) ) $data['items'] = [];
        return $data;
    }

    public static function getUserByEmail($email) {
        $result  = OmsOAuthHttpClient::query('o/ums/user/basicInfo/' . $email. '/email' );
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return array('status'=>200,'data'=>$data['result']);
        }else{
            return array('status'=>500,'msg' =>$result);
        }
    }

    public static function getUserByMobile($mobile) {
        $result  = OmsOAuthHttpClient::query('o/ums/user/basicInfo/' . $mobile . '/mobile');
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return array('status'=>200,'data'=>$data['result']);
        }else{
            return array('status'=>500,'msg' =>$result);
        }
    }
    public static function getUserById($id) {
        $result  = OmsOAuthHttpClient::query('o/ums/user/' . $id .  '/basicInfo',['t'=>time()]);
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return array('status'=>200,'data'=>$data['result']);
        }else{
            return array('status'=>500,'msg' =>$result);
        }
    }

    public static function getAll() {
        $data = OmsOAuthHttpClient::query(LWJ_OAUTH_HOST . 'o/ums/staff/getAll', array(), array());
        $result = json_decode($data,true);
        if(isset($result['code']) && $result['code'] == 0) {
            return array('status'=>200,'data'=>$result['result']);
        }else {
            return array('status'=>500,'msg' =>$data);
        }
    }

    /**
     * 绑定第3放登录
     * @param $data
     * @return array
     *
     * {appCode":"qq","userId":"0","openid":"10000000000000000000"}
     *
     */
    public static function bindOpenId($data) {
        $result  = OmsOAuthHttpClient::put('o/ums/user/bindOpenId',['t'=>time()],$data);
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return array('status'=>200,'data'=>$data['result']);
        }else{
            return array('status'=>500,'msg' =>$result);
        }
    }
    /**
     * 解绑第3放登录
     * @param $data
     * @return array
     *
     * {appCode":"qq","userId":"0","openid":"10000000000000000000"}
     *
     */
    public static function unBindOpenId($data) {
        $result  = OmsOAuthHttpClient::put('o/ums/user/unBindOpenId',['t'=>time()],$data);
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return array('status'=>200,'data'=>$data['result']);
        }else{
            return array('status'=>500,'msg' =>$result);
        }
    }


    public static function getOpenIds($userId,$appCode='null') {
        $result  = OmsOAuthHttpClient::put('o/ums/user/getOpenIds/' . $userId . '/'  . $appCode,[],['t'=>time()]);
        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return $data['result'];
        }else{
            return[];
        }

    }


    public static function getUserIdByOpenid($appCode,$openId) {
        $data = ['appCode'=>$appCode,'userId'=>'XXXXXX','openid'=>$openId];
        $result  = OmsOAuthHttpClient::put('o/ums/user/getUserIdByOpenid/',[],$data);

        $data = json_decode($result,true);
        if(isset($data['code']) && $data['code'] == 0 && isset($data['result'])) {
            return $data['result'];
        }else{
            return '';
        }

    }

}